package com.woniuxy.gateway.handler;

import cn.hutool.json.JSONUtil;
import com.woniuxy.gateway.exception.cinema.CinemaException;
import com.woniuxy.gateway.exception.movieInfo.MovieException;
import com.woniuxy.gateway.exception.movieSession.MovieSessionException;
import com.woniuxy.gateway.exception.sessionTicket.SessionTicketException;
import com.woniuxy.gateway.exception.token.TokenException;
import com.woniuxy.gateway.util.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GloableExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ex.printStackTrace();
        Result<?> result = Result.getResult();
        if(ex instanceof MovieException) {
            MovieException me = (MovieException)ex;
            result.setMsg(me.getMessage()).setCode(me.getCode());
        }
        else if (ex instanceof CinemaException)
        {
            CinemaException me = (CinemaException)ex;
            result.setMsg(me.getMessage()).setCode(me.getCode());
        }
        else if (ex instanceof MovieSessionException)
        {
            MovieSessionException me = (MovieSessionException)ex;
            result.setMsg(me.getMessage()).setCode(me.getCode());
        }
        else if (ex instanceof SessionTicketException)
        {
            SessionTicketException me = (SessionTicketException)ex;
            result.setMsg(me.getMessage()).setCode(me.getCode());
        }
        else if (ex instanceof TokenException)
        {
            TokenException me = (TokenException)ex;
            result.setMsg(me.getMessage()).setCode(me.getCode());
        }
//        else if (ex instanceof SessionTicketException)
//        {
//            SessionTicketException me = (SessionTicketException)ex;
//            result.setMsg(me.getMessage()).setCode(me.getCode());
//        }







        else if(ex instanceof Exception)
            result.setCode(500).setMsg("系统错误");
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        String json = JSONUtil.parse(result).toString();
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            return  exchange.getResponse().bufferFactory().wrap(json.getBytes());
        }));
    }
}
